using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Text;
using System.Web.DomainServices;
using Microsoft.Practices.Unity;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL.PartialClasses;
using Silverlight.Weblog.Server.DAL.Services.Interfaces;

namespace Silverlight.Weblog.Server.DAL
{
    [MetadataType(typeof(CommentMetadata))]
    public partial class Comment
    {
        private string _emailMd5Hash;

        [DataMember]
        public string EmailMD5Hash
        {
            get
            {
                return Md5EncodeText(Email);
            }
            set { _emailMd5Hash = value; }
        }

        private string _clearEmailForNewComment;
        [Required(ErrorMessage = "Please write down your Email.")]
        //[RegularExpression(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]
        [DataMember]
        public string ClearEmailForNewComment
        {
            get { return _clearEmailForNewComment; }
            set
            {
                _clearEmailForNewComment = value;
                this.Email = value;
            }
        }

        /// <summary>
        /// Retrieves the MD5 encoded hash string of the provided input.
        /// </summary>
        /// <param name="text">The input text.</param>
        /// <returns>Returns the MD5 hash string of the input string.</returns>
        protected string Md5EncodeText(string text)
        {
            StringBuilder sb = new StringBuilder();

            byte[] ss = MD5.Create()
                .ComputeHash(Encoding.UTF8.GetBytes(text));
            foreach (byte b in ss)
            {
                sb.Append(b.ToString("X2"));
            }
            return sb.ToString().ToLower();
        }
    }

    public class CommentMetadata
    {
        [Include]
        public object BlogPost;

        [Include]
        public object ParentComment;

        [Include]
        public object ChildComments;

        [Required(ErrorMessage = "Please write down your Name.")]
        public object Name;

        [Exclude]
        public object Email;

        [Required(ErrorMessage = "Please write down your Comments.")]
        public object HTML;
    }
}